import { onActivated, onDeactivated, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAppStore } from '@/store/app'
import { useFollowStore } from '@/store/home/follow'
import { TYPES, on } from '@/utils/state-broadcast'
import { useNavRefresh } from '@/compositions/nav/refresh'
import { NAVS } from '@/constant'

export function useFollow() {
  const followStore = useFollowStore()
  const { noFollowAnyone, creatorList } = storeToRefs(followStore)
  const { creatorNextPage, init, refresh } = followStore

  const accountStore = useAccountStore()
  const { isLogin } = storeToRefs(accountStore)

  const appStore = useAppStore()
  const { videoMuted } = storeToRefs(appStore)
  const { toggleVideoMuted } = appStore

  // 換頁回來發現到其他頁有追蹤人就刷新
  const followMap = {}
  onActivated(() => {
    if (Object.values(followMap).some((v) => v) && noFollowAnyone.value) {
      refresh(isLogin.value)
    }
    checkVideoMuted()
  })

  // 強制靜音，且離開本頁要調回去
  let prevVideoMuted
  function checkVideoMuted() {
    if (noFollowAnyone.value) {
      prevVideoMuted = videoMuted.value
      if (!prevVideoMuted) {
        toggleVideoMuted()
      }
    }
  }
  onDeactivated(() => {
    if (typeof prevVideoMuted === 'boolean' && !prevVideoMuted) {
      toggleVideoMuted()
    }
  })

  const cancelFollowObserve = on(TYPES.FOLLOW, (aff, isFollow) => {
    creatorList.value.forEach((data) => {
      if (data.aff === aff) {
        data.is_follow = isFollow
      }
    })
    followMap[aff] = isFollow
  })
  onUnmounted(cancelFollowObserve)

  // nav 點擊原本頁面刷新
  useNavRefresh(NAVS.HOME, () => refresh(isLogin.value))

  return {
    noFollowAnyone,
    creatorList,
    init,
    next: creatorNextPage,
  }
}
